#!/bin/bash
#author: <fanyuantao>
#date: 2024-08-08
#desc: This script is used to scan alive ip in a subnet.

function check_alive_ip() {
    echo "please input will scan ip"
    echo "Exampe: 192.168.8.8"
    read -p "The Server IP : " ip

    if [[ $ip =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then
        ping -c 1 -W 1 $ip &>/dev/null
        if [ $? -eq 0 ]; then
            echo "The host $ip is alive"
        else
            echo "The host $ip is dead"
        fi
        echo "Scan complete"
    else
        echo "Invalid ip format, please input again"
        check_alive_ip
    fi
}

function check_alive_subnet() {
    
    echo "please input will scan subnet"
    echo "Exampe: 192.168.8"
    read -p "The IP Subnet: " subnet

    if [[ $subnet =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then
        echo "Start to scan subnet $subnet.0/24"
        for i in {1..254}; do
            ip="$subnet.$i"
            ping -c 1 -W 1 $ip &>/dev/null
            if [ $? -eq 0 ]; then
                echo "The host $ip is alive"
            fi
        done
        echo "Scan complete"
    else
        echo "Invalid subnet format, please input again"
        check_alive_subnet
    fi
}

function select_scan_mode() {
    while true; do
        echo ""
        echo "Please select scan mode:"
        echo "  1. Scan a single IP"
        echo "  2. Scan a subnet"
        echo "  0. Exit"
        read -p "Your choice: " choice
        case $choice in
            1) check_alive_ip;;
            2) check_alive_subnet;;
            0) exit;;
            *) echo "Invalid choice, please input again.";;
        esac
    done
}

function main() {
    select_scan_mode
}

main